package com.sqs.handler;

import com.sqs.constant.ExceptionConstant;
import com.sqs.constant.SQLConstant;
import com.sqs.exception.BaseException;
import com.sqs.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.validation.FieldError;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.stream.Collectors;

/**
 * 全局异常处理奇器，处理项目中抛出的业务异常
 * */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理自定义业务异常
     * */
    @ExceptionHandler(BaseException.class)
    public Result<?> handleBusinessException(BaseException ex) {
        return Result.error(ex.getCode(), ex.getMessage());
    }

    /**
     * 捕获SQL异常,此处用于抛出数据用户名重复时的错误
     * @param ex
     * @return
     * */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        String message = ex.getMessage();
        if(message.contains(SQLConstant.SQLException)){
            return Result.error(ExceptionConstant.CODE_409, ExceptionConstant.USER_EXIST);
        }
        else {
            return Result.error(ExceptionConstant.CODE_500, ExceptionConstant.UNKNOWN_ERROR);
        }
    }

    /**
     * 处理参数校验异常（如@Validated失败）
     * */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<?> handleValidationException(MethodArgumentNotValidException ex) {
        String errorMsg = ex.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(", "));
        return Result.error(ExceptionConstant.CODE_400, ExceptionConstant.PARAM_ERROR + errorMsg);
    }

    /**
     * 兜底处理其他异常
     * */
    @ExceptionHandler(Exception.class)
    public Result<?> handleOtherException(Exception ex) {
        log.error("系统异常: ", ex);
        return Result.error(ExceptionConstant.CODE_500, ExceptionConstant.SYSTEM_BUSY);
    }
}
